package com.qdxwx.web.controller.course;

import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.book.BookService;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.course.*;
import com.qdxwx.data.service.favorite.FavoriteService;
import com.qdxwx.data.service.teacher.TeacherService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.channel.Channel;
import com.qdxwx.models.course.*;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.enums.WebsiteProfileType;
import com.qdxwx.models.teacher.Teacher;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Course接口
 * @author developer
 */
@Controller
@RequestMapping("/course")
public class CourseViewController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CourseViewController.class);
	@Autowired
	private CourseService courseService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private FavoriteService favoriteService;
	@Autowired
	private CourseNodeService courseNodeService;
	@Autowired
	private WebsiteProfileService websiteProfileService;
	@Autowired
	private CourseStudyHistoryService courseStudyHistoryService;
	@Autowired
	private CourseFileService courseFileService;
	@Autowired
	private ChannelService channelService;
	@Autowired
	private BookService bookService;
	@Autowired
	private UserBuyService userBuyService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserService userService;

	/**
	 * 课程详情
	 */
	@GetMapping("/view/{id:[0-9]+}.html")
	public String courseInfo(HttpServletRequest request, @PathVariable("id") int courseId, ModelMap model) {
		User user = LoginUser.getUser(request);
		//兼容分享处理
		if (user != null && TKConvert.toInteger(request.getParameter("uid")) == 0) {
			long uid = TKConvert.toLong(request.getParameter("uid"));
			if (uid == 0 || uid != user.getUserId()) {
				return "redirect:/course/view/" + courseId + ".html?uid=" + user.getUserId();
			}
		}
		// 查询课程详情
		Course course = courseService.get(courseId);
		//如果课程为空或者为删除状态则不能查看课程
		if (ObjectUtils.isNull(course) || course.getIsAvailable() == 3) {
			return VIEW_ERROR_404;
		}
		Channel channel = channelService.get(course.getChannelId());
		if (channel == null) {
			return toErrorView(request, "找不到对应的频道！");
		}
		//禁用的频道
		if (channel.getIsDisabled() == 1) {
			return toErrorView(request, "当前频道已被禁用！");
		}
		//判断是否属于模块
		if (channel.getModuleId() != ModuleType.COURSE.ordinal()) {
			logger.error("当前频道归属错误！");
			logger.error(channel.toString());
			return toErrorView(request, "当前频道归属错误！");
		}
		//课程章节目录村
		List<CourseNode> courseNodeTree = courseNodeService.getTreeByCourseId(courseId);
		if (user != null) {
			courseStudyHistoryService.setIsStudy(courseNodeTree, user.getUserId(), courseId);
		}
		model.put("courseNodeTree", courseNodeTree);
		//如果是直播
		if (course.getSellType().equals("LIVE")) {
			//购买服务开关
			Map<String, Object> serviceSwitch = websiteProfileService.getMap(WebsiteProfileType.serviceSwitch.toString());
			if (!serviceSwitch.get("live").toString().equals("ON")) {
				request.setAttribute("msg", "系统未启用【直播】功能，无法查看！");
				return VIEW_ERROR;
			}
			return "redirect:/live/view/" + courseId + ".html";
		}
		//如果是套餐
		if (course.getSellType().equals("PACKAGE")) {
			List<CourseDTO> courseDTOList = courseService.getListByPackageId(courseId);
			model.put("courseDTOList", courseDTOList);
			//获得第一个课程id
			model.put("firstCourseId", ObjectUtils.isNotNull(courseDTOList) ? courseDTOList.get(0).getCourseId() : 0);
		}
		//判断该课程是否可以观看

		model.put("course", course);
		//更新课程的浏览量
		courseService.updateView(courseId);
		//查询课程老师
		List<Teacher> teachers = teacherService.getListByCourseId(courseId);
		model.put("teachers", teachers);
		//相关课程
		List<CourseDTO> courseList = courseService.getInterfixList(course, 4);
		model.put("courseList", courseList);

		if (user != null) {
			boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.COURSE.ordinal(),courseId);
			//查询是否已经收藏
			boolean isFavorite = favoriteService.isExist(user.getUserId(), courseId, ModuleType.COURSE.ordinal());
			UserAccount account = userAccountService.getByUserId(user.getUserId());
			model.put("isBuy", isBuy);
			model.put("isFavorite", isFavorite);
			model.put("user", user);
			model.put("userId", user.getUserId());
			model.put("userMoney", account.getBalance());
		} else {
			model.put("isBuy", false);
			model.put("isFavorite", false);
			model.put("userId", 0);
			model.put("userMoney", 0);
		}

		//查询课程所属套餐集合
		/*
		List<CourseDTO> packageCourses = courseService.getPackageParents(courseId);
		for (CourseDTO courseDTO : packageCourses) {
			//根据套餐id获取套餐下的课程
			List<CourseDTO> courseDTOList = courseService.getListByPackageId(courseDTO.getCourseId());
			//套餐下的课程集合
			courseDTO.setCourseList(courseDTOList);
		}
		model.put("packageCourses", packageCourses);
		*/
		String intro = TKString.trim(TKString.clearHTML(course.getIntro()));
		if (intro.length() > 1) {
			intro = intro.replace("\n", "");
			intro = intro.replace("\r", "");
			intro = TKString.left(intro, 120);
		}
		model.put("pageDescription", intro);

		model.put("channel", channel);
		model.put("channelId", course.getChannelId());
		List<CourseFile> courseFiles = courseFileService.getList(courseId);
		model.put("courseFiles", courseFiles);
		//查询课程最近被观看到章节
		if (user != null) {
			CourseStudyHistory lastTimeStudyHistory = courseStudyHistoryService.getLastByUserId(user.getUserId(), courseId);
			model.put("lastTimeStudyHistory", lastTimeStudyHistory);
		}
		if (course.getBookId() > 0) {
			model.put("book", bookService.get(course.getBookId()));
		}
		int learnedUserCount = userBuyService.countByCourseId(courseId);
		model.put("learnedUserCount", learnedUserCount);
		if (learnedUserCount > 0) {
			//学习此课程的人 (最新8个)
			@SuppressWarnings("unchecked")
			List<User> learnedUsers = (List<User>) CacheUtils.get(CacheConstants.COURSE_LEARNED_PREFIX + "course" + courseId);
			if (learnedUsers == null || learnedUsers.size() == 0) {
				learnedUsers = userService.getLatelyStudentList(courseId, 8);
				;
				CacheUtils.set(CacheConstants.COURSE_LEARNED_PREFIX + "course" + courseId, learnedUsers, 6000);//缓存5分钟
			}
			model.put("learnedUsers", learnedUsers);
		}
		if (TKRequest.isMobileBrowse(request)) {
			return getViewPathH5("course/course-view");
		}
		return getViewPath("course/course-view");
	}
}